package dumu

import (
	"encoding/json"
	"errors"
	"fsdvgw/repo"
)

const (
	CommandRegisterUser = "RegUser"
	CommandDeleteUser   = "DelUser"
	CommandOpenGate     = "OpenGate"
)

func Execute(dev *repo.Dev, command string, commandInfo map[string]any) (any, error) {
	switch command {
	case CommandRegisterUser:
		param, err := buildParam[registerUserParam](commandInfo)
		if err != nil {
			return nil, err
		}
		return newDumu(dev).registerUser(param)
	case CommandDeleteUser:
		param, err := buildParam[removeUserParam](commandInfo)
		if err != nil {
			return nil, err
		}
		return newDumu(dev).removeUser(param)
	default:
		return nil, errors.New("度目设备不支持" + command + "操作")
	}
}

func buildParam[T any](commandInfo map[string]any) (*T, error) {
	param := new(T)
	bytes, err := json.Marshal(commandInfo)
	if err != nil {
		return param, err
	}

	err = json.Unmarshal(bytes, param)
	if err != nil {
		return param, err
	}
	return param, nil
}
